from urllib import request, parse
from lxml import etree
import ssl
import re

# 取消 https 代理验证
ssl._create_default_https_context = ssl._create_unverified_context


def dyldplay(self, line, link):
    # 报头
    # user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'
    user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    headers = {'User-Agent': user_agent}
    # url = "https://v.qq.com/x/search/?q=%E9%99%88%E6%83%85%E4%BB%A4"
    url = link
    dyld_url = ''
    if line == '1':
        dyld_url = "http://dianyingleida.com"
    elif line == '2':
        dyld_url = "http://www.nmkan.com"
    req = request.Request(url, headers=headers)
    try:
        response = request.urlopen(req)
        # 获取每页的HTML源码字符串
        html = response.read().decode('utf-8')
        # 解析html 为 HTML 文档
        selector = etree.HTML(html)

        search = selector.xpath('//div[@class="embed-responsive clearfix"]/script[1]/text()')[0]
        url = re.findall('(?<=now=").*?(?=";)', search)[0]
        type = re.findall('(?<=pn=").*?(?=";)', search)[0]
        prePage = dyld_url + re.findall('(?<=prePage=").*?(?=";)', search)[0]
        nextPage = dyld_url + re.findall('(?<=nextPage=").*?(?=";)', search)[0]
        if type == '33uu':
            url = '' + url
        elif type == 'kkyun':
            url = '' + url
        elif type == 'kuyun ':
            url = '' + url
        elif type == 'zkyun':
            url = '' + url
        elif type == 'zuidall':
            url = '' + url
        elif type == 'ckm3u8':
            if line == '1':
                url = 'http://www.dplayer.tv/?url=' + url
            elif line == '2':
                url = 'http://www.nmkan.com/play/chplayer/chplayer.html?videourl=' + url
        elif type == 'kkm3u8':
            url = 'https://www.kuyunjiexi.com/?url=' + url
        elif type == 'zkm3u8':
            url = 'http://api.sztw.net/m3u8.php?url=' + url
        elif type == 'zuidam3u8':
            url = 'https://zuidajiexi.net/m3u8.html?url=' + url
        elif type == '33uuck':
            url = 'http://api.123zx.net/m3u8/play.html?id=' + url
        elif type == 'dbm3u8':
            url = "http://www.dbzyz.com/m3u8.php?url=" + url
        elif type == 'dbyun':
            url = '' + url
        elif type == '33uuck':
            url = 'http://api.123zx.net/m3u8/play.html?id=' + url
        elif type == '33uu':
            url = '' + url
        else:
            url = url

        result = {
            "url": url,
            "prePage": prePage,
            "nextPage": nextPage,
        }
        return result
    except Exception:
        print(url, Exception)
        data = {"code": -1, "message": "error", "data": None}
        return data
